package com.lu.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lu.common.annotation.SystemLog;
import com.lu.common.vo.Result;
import com.lu.sys.entity.Role;
import com.lu.sys.service.IRoleService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.role;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lulu
 * @since 2023-04-04
 */
@Api(tags = {"角色接口列表"})
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;



    @GetMapping("/list")
    public  Result<Map<String,Object>> getRoleList(@RequestParam(value = "roleName",required = false) String roleName,
                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                   @RequestParam(value = "pageSize") Long pageSize){
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(roleName),Role::getRoleName,roleName);
        wrapper.orderByDesc(Role::getRoleId);//用户列表按照降序排序

        Page<Role> page = new Page<>(pageNo,pageSize);
        roleService.page(page,wrapper);

        Map<String,Object> data = new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());

        return Result.success(data);
    }

    @PostMapping
    @SystemLog("新增角色")
    public Result<?> addRole(@RequestBody Role role){//RequestBody可以把json数据转换为role对象
        roleService.addRole(role);
        return Result.success("新增角色成功");
    }

    @PutMapping
    @SystemLog("更新角色")
    public Result<?> updateRole(@RequestBody Role role){
        roleService.updateRole(role);
        return Result.success("修改角色成功");
    }

    @GetMapping("/{id}")
    public Result<Role> getRoleById(@PathVariable("id") Integer id){  //点击修改按钮后从数据库中查询信息的接口
        Role role = roleService.getRoleById(id);
        return Result.success(role);
    }

    //使用逻辑删除,在yml中导入配置
    @DeleteMapping("/{id}")
    @SystemLog("删除角色")
    public Result<Role> deleteRoleById(@PathVariable("id") Integer id){  //点击修改按钮后从数据库中查询信息的接口
        roleService.deleteRoleById(id);
        return Result.success("删除角色成功");
    }

    //获取所有角色
    @GetMapping("/all")
    public Result<List<Role>> getAllRole(){
        List<Role> roleList = roleService.list();
        return Result.success(roleList);
    }
}
